"""
@Project ：HD_project
@File    ：new_request.py
@IDE     ：PyCharm
@Author  ：靓仔
@Date    ：2023/12/5 0005 8:58
"""
import time
import json
from concurrent.futures import ThreadPoolExecutor
import concurrent.futures
from api_requests.temporary_plan.config import session_request, session_login
from utils.new_time import get_time_of_day, new_time, get_temporary_plan
from utils.remove_list_tool import list_remove


class ApiHd:
    def __init__(self):
        self.session = session_request
        self.headers = {
            'Accept': 'application/json, text/plain, */*',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Autothrowerror': 'true',
            'Connection': 'keep-alive',
            'Content-Length': '80',
            'Content-Type': 'application/json;charset=UTF-8',
            'Ctp-T-Code': '0002200000080659',
            'Host': '10.6.10.110',
            'Origin': 'http://10.6.10.110',
            'Ratio': '945*1512',
            'Referer': 'http://10.6.10.110/',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)'
                          'Chrome/119.0.0.0 Safari/537.36',
        }
        self.user_id = session_login()

    # def session_login(self):
    #     _url = "http://10.6.10.110/jadp-api/auth/session"
    #     data = {"account": "yanzhi", "password": "DZDR1M81FcALjaYAXpRv/nSA2kYcWRXemwE09Txa1AU="}
    #     res = json.loads(self.session.post(url=_url, json=data, headers=self.headers).text)
    #     res = res["result"]["data"]["user"]["userId"]
    #     return res

    # 获取当前用户下的所有待办信息
    def get_pant_info(self):
        _url = "http://10.6.10.110/bd-grsx-api/todo/page/collapse"
        data = {"bllx": "2", "userId": self.user_id, "xtbs": "10011006"}
        res = self.session.post(url=_url, json=data, headers=self.headers).text
        return res

    # 新增临时计划和新增临时计划制度计划明细表且提交
    def add_temporary_plan_details(self):
        _url = "http://10.6.10.110/zdgl-api/common/data/show"
        _data = {"xtbs": "10011006", "docType": "4",
                 "data": {"docId": "", "templateId": "24DEE203B7F146099DC072134243CC6F", "templateType": "4",
                          "activityDefId": "CREATE_ACTIVITY"}}
        res = json.loads(self.session.post(url=_url, json=_data, headers=self.headers).text)
        # fristActivityDefId = res["result"]["formTemplate"]["fristActivityDefId"]
        processdefName = res["result"]["formTemplate"]["processdefName"]
        processdefId = res["result"]["formTemplate"]["processdefId"]

        # noinspection PyShadowingNames
        def get_plan_id():
            plan_url = "http://10.6.10.110/zdgl-api/common/data"
            plan_data = {"xtbs": "10011006", "docType": "4",
                         "data": {"primaryValue": None, "reason": None, "endDate": None, "hqr": None, "pageSize": 20,
                                  "idList": None, "ngrq": None, "sfyhq": None,
                                  "templateId": "24DEE203B7F146099DC072134243CC6F", "itemName": "", "pageNo": 1,
                                  "ngrName": None, "beginTime": None, "sortNames": [], "cascadeSubQueryResult": None,
                                  "item": "制度计划", "cascadeSubQueryCondition": None, "activityName": None,
                                  "updatorId": None, "bzbms": [
                                 {"jgjb": "5", "orgStructureId": "CB0F6F1B7D534AF2BFAD00B40F9D514B", "zzjgxsfw": None,
                                  "orgId4A": "20000048", "ffbmlzfs": None, "sfgkbm": "1", "orgLevel": 0,
                                  "orgId": "20000048",
                                  "nameFullPath": "哈尔滨电气集团有限公司/哈电集团（本部）/法律合规部", "orgType": 7,
                                  "jhzxbm": None, "children": [], "orgCode": "20000048", "fwdz": None, "orgProperty": 1,
                                  "bmnbglld": None, "state": 1, "qzh": None, "orgName": "法律合规部",
                                  "corpId": "20000001", "gwjhdwbm": None, "shortSpell": "flhgb", "deptId": "20000048",
                                  "sortNo": 0, "nblx": "2", "sfgz": None, "sfcybmhq": None, "xsfw": None,
                                  "parentOrgId": "20000003", "simpleName": None, "fullSpell": "falvheguibu",
                                  "fwjg": None, "sapHROrgId": None, "userId": "20000048",
                                  "employeeName": "法律合规部"}], "ngbmName": "法律合规部", "_id": None,
                                  "flowStatus": None, "tbjzTime": "2023-12-05", "thhj": None, "dwid": None,
                                  "creatorId": None, "remark": get_temporary_plan(), "sortTypes": [],
                                  "delFlag": None, "title": get_temporary_plan(),
                                  "searchText": None, "docStatus": None, "sqxz": "临时计划", "ngr": None,
                                  "sortFields": [], "primaryName": "ID", "updateTime": None, "url": None,
                                  "actionType": None, "beginDate": None, "createTime": None, "cshqry": None,
                                  "sortType": "", "templateName": None, "ngbm": "20000048", "endTime": None,
                                  "sortFieldName": None, "jsbzflList": [
                                 {"yjbzfl": "1", "yjbzflName": "101标准化工作导则", "name": "101标准化工作导则",
                                  "code": "1", "label": "101标准化工作导则", "value": "1"},
                                 {"yjbzfl": "2", "yjbzflName": "102通用技术语言标准", "name": "102通用技术语言标准",
                                  "code": "2", "label": "102通用技术语言标准", "value": "2"},
                                 {"yjbzfl": "3", "yjbzflName": "103量和单位", "name": "103量和单位", "code": "3",
                                  "label": "103量和单位", "value": "3"},
                                 {"yjbzfl": "4", "yjbzflName": "104数值与数据", "name": "104数值与数据", "code": "4",
                                  "label": "104数值与数据", "value": "4"},
                                 {"yjbzfl": "5", "yjbzflName": "105互换性与精度标准及实现系列标准",
                                  "name": "105互换性与精度标准及实现系列标准", "code": "5",
                                  "label": "105互换性与精度标准及实现系列标准", "value": "5"}], "zddjList": [
                                 {"primaryValue": "85A39DE65AEB4BE6B6A13D7E695E7EE8", "dwid": "default", "code": "1",
                                  "codeType": "15007", "codeTypeName": None, "dwmc": "", "creatorId": "SuperAdmin",
                                  "orderNum": 1, "pageSize": 20, "primaryName": "ID", "sortTypes": [],
                                  "updateTime": "2023-11-11 16:15:33", "idList": None,
                                  "updatorId": "1CCC16D0F29A47CE9CAD8E7EF4372505", "actionType": None,
                                  "createTime": "2023-02-23 08:59:30", "sortType": "", "pageNo": 1,
                                  "name": "基本管理制度", "sortFields": [], "_id": None,
                                  "id": "85A39DE65AEB4BE6B6A13D7E695E7EE8", "sortNames": [], "sortFieldName": None,
                                  "label": "基本管理制度", "value": "1"},
                                 {"primaryValue": "9CFE41DB5E3648D8A75E42F05C01F55E", "dwid": "default", "code": "2",
                                  "codeType": "15007", "codeTypeName": None, "dwmc": "", "creatorId": "SuperAdmin",
                                  "orderNum": 2, "pageSize": 20, "primaryName": "ID", "sortTypes": [],
                                  "updateTime": "2023-11-11 16:16:29", "idList": None,
                                  "updatorId": "1CCC16D0F29A47CE9CAD8E7EF4372505", "actionType": None,
                                  "createTime": "2023-02-23 08:59:39", "sortType": "", "pageNo": 1,
                                  "name": "重要管理制度", "sortFields": [], "_id": None,
                                  "id": "9CFE41DB5E3648D8A75E42F05C01F55E", "sortNames": [], "sortFieldName": None,
                                  "label": "重要管理制度", "value": "2"},
                                 {"primaryValue": "67E7B5193E094A5A858310FA1060D2BA", "dwid": "default", "code": "3",
                                  "codeType": "15007", "codeTypeName": None, "dwmc": "", "creatorId": "SuperAdmin",
                                  "orderNum": 3, "pageSize": 20, "primaryName": "ID", "sortTypes": [],
                                  "updateTime": "2023-11-11 16:16:38", "idList": None,
                                  "updatorId": "1CCC16D0F29A47CE9CAD8E7EF4372505", "actionType": None,
                                  "createTime": "2023-02-23 08:59:58", "sortType": "", "pageNo": 1,
                                  "name": "一般管理制度", "sortFields": [], "_id": None,
                                  "id": "67E7B5193E094A5A858310FA1060D2BA", "sortNames": [], "sortFieldName": None,
                                  "label": "一般管理制度", "value": "3"}], "templateType": "4"}}
            plan_res = json.loads(self.session.post(url=plan_url, json=plan_data, headers=self.headers).text)
            if plan_res["result"]:
                return plan_res["result"]

        plan_res = get_plan_id()

        def get_id_from_response(id_type):
            """
            从 API 响应中获取指定类型的 ID

            Parameters:
            - id_type: ID 的类型，可以是 "docId" 或 "todoId"

            Returns:
            - 如果找到对应类型的 ID，则返回该 ID；否则返回 None
            """
            api_data = plan_res
            try:
                return api_data[id_type]
            except KeyError:
                return None

        def plan_id():
            return get_id_from_response("docId")

        def todo_id():
            return get_id_from_response("todoId")

        plan_id = plan_id()

        # 获取后续的流程名称
        def handle_process_flow():
            flow_url = "http://10.6.10.110/zdgl-api/bxryStrategy/bxryNode"
            flow_data = {"processdefId": processdefId, "processdefName": processdefName,
                         "businessId": plan_id, "nodeId": "zdgl_zdjh_nwzb_jhsq",
                         "xtbs": "10011006", "processInstId": "", "activityInstId": ""}
            flow_response = json.loads(self.session.post(url=flow_url, json=flow_data, headers=self.headers).text)

        def create_temporary_plan_details(nums):
            for a in range(1, nums + 1):
                create_temporary_plan_details_url = "http://10.6.10.110/zdgl-api/institution"
                create_temporary_plan_details_data = {"zbbmName": "法律合规部", "zbbm": "20000048", "item": "规章制度",
                                                      "code": "无", "planType": "8",
                                                      "name": get_temporary_plan() + "_" + str(a), "level": "1700101",
                                                      "zdxlbh": "170010102", "zdcj": "2",
                                                      "completeTime": "2023-12-07 00:00:00",
                                                      "trainingCompleteTime": "2023-12-07 00:00:00",
                                                      "remark": get_temporary_plan() + "_" + str(a),
                                                      "institutionRuleName": get_temporary_plan() + "_" + str(a),
                                                      "planId": plan_id}
                json.loads(
                    self.session.post(url=create_temporary_plan_details_url, json=create_temporary_plan_details_data,
                                      headers=self.headers).text)
                print(f"制度计划明细新增完成{a}")
                time.sleep(0.3)

        def submit_todo():
            submit_todo_url = "http://10.6.10.110/zdgl-api/common/submit"
            submit_todo_data = {"xtbs": "10011006", "docType": "4", "data": {"nextParticipantMap": {
                "zdgl_zdjh_nwzb_bmnbsh_user": [
                    {"id": "8D37B6FC4AA847B3B4055435B92DEDA1", "name": "颜值", "typeCode": "person", "bllx": "2",
                     "role": "主办部门处长", "dblx": ""}]}, "nextActivityDefId": "zdgl_zdjh_nwzb_bmnbsh", "spyj": "",
                "spjg": "1", "operateType": "1",
                "todoId": todo_id(),
                "sfyy": "2", "extend": "{\"bmhqList\":[]}",
                "ywbs": "100", "sccldry": "", "pbzlc": ""}}
            json.loads(self.session.post(url=submit_todo_url, json=submit_todo_data, headers=self.headers).text)
            print("提交完成")

        create_temporary_plan_details(5)
        handle_process_flow()
        submit_todo()

    # 获取单位下的规章制度docid
    def get_doc_id(self):
        dic_id_list = []
        url = "http://10.6.10.110/zdgl-api/qc/page"
        data = {"lclx": "2", "flowStatus": None, "dqhj": None, "zbbmName": "", "zbbm": "", "sfybg": "", "pageNo": 1,
                "pageSize": 500, "sfdwqc": 1}
        res = json.loads(self.session.post(url=url, json=data, headers=self.headers).text)
        for dic_id in res["result"]["list"]:
            dic_id_list.append(dic_id["docId"])
        return dic_id_list

    # 承接清单接口
    def get_inventory_list(self, data):
        nums = 0
        for dic_id in data:
            nums += 1
            url = "http://10.6.10.110//zdgl-api/acceptance/oaCallback"
            data = {"id": dic_id}
            res = self.session.post(url=url, json=data, headers=self.headers).text
            print(f"{nums}:", res)

    def run_get_inventory_list(self):
        datas = list_remove(20, self.get_doc_id())
        with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
            # 使用 as_completed 迭代已完成的 futures
            futures = [executor.submit(self.get_inventory_list, data) for data in datas]
            for future in concurrent.futures.as_completed(futures):
                try:
                    # 获取已完成 future 的结果（这将阻塞，直到 future 完成）
                    result = future.result()
                except Exception as e:
                    print("发生错误:", e)

    # 正式印发、完成宣贯消息通知接口
    def institution_rule(self):
        url = "http://10.6.10.110//zdgl-api/institutionRule/taskDemo"
        data = {"type": "2", "overdueDay": -1,
                # todo_id
                "activityDefId": "26F616F390074B0F88C22D00CF6F1CA1",
                # "content": "%s制度在印发环节停留一个月未处理，请及时处理。"
                "content": "%s制度在宣贯环节停留三个月未处理，请及时处理。"
                }
        res = self.session.post(url=url, json=data, headers=self.headers).text
        print(res)


if __name__ == '__main__':
    ApiHd().run_get_inventory_list()
    # ApiHd().institution_rule()
    # ApiHd().get_inventory_list()
